﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using AMM.Business;
using AMM.Business.Store;
using AMM.CustomWinControls;
using AMM.Model;
using AMM.Model.PrintModels;
using AMM.Model.Store;
using AMM.UserControls;
using Microsoft.Reporting.WinForms;

namespace AMM.Forms.Store {
    public partial class FrmOutStoreOrder : FrmOutStoreOrderBase {

        private int _pageIndex;
        private OutStoreOrderSearchModel _searchModel;
        private OutStoreOrderProcessor _outStoreOrderProcessor;
        private List<OutStoreOrderViewModel> _outStoreOrderList;

        #region Override

        protected override string FunctionCode {
            get { return "AMM1413"; }
        }

        protected override BaseSearchControl SearchControl {
            get { return new OutStoreOrderSearchControl(); }
        }

        protected override void Add() {
            this.ResetForms();
            this.ShowEditForm("新增", new OutStoreOrder() { ClassStatus = ClassStatus.Added });
            base.Add();
        }

        protected override void Amend() {
            List<OutStoreOrderViewModel> selectedList = this.dgvOutStoreOrderList.GetSelectedRows<OutStoreOrderViewModel>();
            if (selectedList.Count > 1) { this.OnlySelectSingleRecord(); return; }
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            OutStoreOrder outStoreOrder = this._outStoreOrderProcessor.FetchOutStoreOrderById(selectedList[0].Key);

            outStoreOrder.ClassStatus = ClassStatus.Updated;
            this.ShowEditForm("修改", outStoreOrder);
            base.Amend();
        }

        protected override void Save() {
            base.Save();
        }

        protected override void Delete() {
            List<OutStoreOrderViewModel> selectedList = this.dgvOutStoreOrderList.GetSelectedRows<OutStoreOrderViewModel>();
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            this.CreateNewThread(() => {
                this.PreventCancel = true;
                this._outStoreOrderProcessor.Delete(selectedList.Select(x => x.Key).ToArray());
                this.MDIParent.SetStatusInformation("删除成功");
            }, () => {
                this.ResetForms();
                this.PreventCancel = false;
                base.Delete();
            });
        }

        protected override void Print() {
            List<OutStoreOrderViewModel> selectedList = this.dgvOutStoreOrderList.GetSelectedRows<OutStoreOrderViewModel>();
            if (selectedList.Count > 1) { this.OnlySelectSingleRecord(); return; }
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            this.CreateNewThread(() => {
                string deviceInfo =
                  "<DeviceInfo>" +
                  "  <OutputFormat>EMF</OutputFormat>" +
                  "  <PageWidth>21.5cm</PageWidth>" +
                  "  <PageHeight>27.8cm</PageHeight>" +
                  "  <MarginTop>0cm</MarginTop>" +
                  "  <MarginLeft>0cm</MarginLeft>" +
                  "  <MarginRight>0cm</MarginRight>" +
                  "  <MarginBottom>0cm</MarginBottom>" +
                  "</DeviceInfo>";

                PrintDataSoruceHelper printDataSoruceHelper = new PrintDataSoruceHelper();
                List<PrintOutStoreOrder> printOutStoreOrder = printDataSoruceHelper.FetchPrintOutStoreOrder(selectedList[0].Key);
                List<PrintOutStoreOrderDetails> printOutStoreOrderDetails = printDataSoruceHelper.FetchPrintOutStoreOrderDetails(selectedList[0].Key);

                this.PrintHelperIns = new PrintHelper("OutStoreOrderPrint.rdlc", this.Text, deviceInfo);
                this.PrintHelperIns.ReportDataSources.Add(new ReportDataSource("ds", printOutStoreOrder));
                this.PrintHelperIns.ReportDataSources.Add(new ReportDataSource("ds1", printOutStoreOrderDetails));
                base.Print();
            }, () => {
                // for hiding
                this.PrintHelperIns.Dispose();
            });
        }

        protected override void Search(object sender, FrmSearch.SearchArgs e) {
            this.CreateNewThread(() => {
                if (e.IsRevert) {
                    this._searchModel = new OutStoreOrderSearchModel();
                }
                else {
                    this._searchModel = (OutStoreOrderSearchModel)e.SearchModel;
                }
            }, () => {
                this.BindOutStoreOrderList();
            });
        }

        #endregion

        public FrmOutStoreOrder() {
            InitializeComponent();

            this.dgvOutStoreOrderList.DataGridViewModelType = typeof(OutStoreOrderViewModel);
            this.dgvOutStoreOrderDetailList.DataGridViewModelType = typeof(OutStoreOrderDetailsViewModel);
        }

        #region Private methods

        private bool frmEdit_Edit(object sender, FrmEdit.EditArgs e) {
            bool resultFlag = false;
            OutStoreOrder outStoreOrder = (OutStoreOrder)e.EditModel;
            if (outStoreOrder.OutStoreOrderDetails.Count == 0) {
                this.ShowError("请添加订单明细记录！");
                return false;
            }
            if (outStoreOrder.OutStoreOrderDetails.Any(x => !string.IsNullOrEmpty(x.ErrMessage))) {
                this.ShowError("请清除明细表错误信息后尝试保存操作！");
                return false;
            }
            this.PreventCancel = true;
            this.CreateNewThread(() => {
                if (outStoreOrder.ClassStatus == ClassStatus.Added) {
                    outStoreOrder.CreatedBy = LoginUserName;
                    this._outStoreOrderProcessor.Insert(outStoreOrder);
                }
                else {
                    outStoreOrder.ModifiedBy = LoginUserName;
                    this._outStoreOrderProcessor.Update(outStoreOrder);
                }
                resultFlag = true;
            }, () => {
                this.ResetForms();
                this.PreventCancel = false;
                if (resultFlag) {
                    this.MDIParent.SetStatusInformation("保存成功");
                    this.FormEdit.Close();
                }
            });

            this.Save();
            return true;
        }

        private void ResetForms() {
            this.BindOutStoreOrderList();
            this.BindOutStoreOrderDetailsList(0);
        }

        private void BindOutStoreOrderList() {
            this.CreateNewThread(() => {
                this._outStoreOrderList = this._outStoreOrderProcessor.FetchOutStoreOrderViewModelList(this._searchModel, this._pageIndex);
            }, () => {
                this.dgvOutStoreOrderList.DataSource = new SortableBindingList<OutStoreOrderViewModel>(this._outStoreOrderList);
                this.pceList.Records = this._searchModel.Records;
                this.pceList.DataBind();
            });
        }

        private void BindOutStoreOrderDetailsList(int outStoreId) {
            List<OutStoreOrderDetailsViewModel> detailsList = new List<OutStoreOrderDetailsViewModel>();
            this.CreateNewThread(() => {
                if (outStoreId != 0) {
                    detailsList = this._outStoreOrderProcessor.FetchOutStoreOrderDetailsViewModelList(outStoreId);
                }
            }, () => {
                this.dgvOutStoreOrderDetailList.DataSource = new SortableBindingList<OutStoreOrderDetailsViewModel>(detailsList);
            });
        }

        private void ShowEditForm(string title, OutStoreOrder outStoreOrder) {
            this.CreateNewThread(() => {
                Thread.Sleep(100);
            }, () => {
                OutStoreOrderEditControl editControl = new OutStoreOrderEditControl();
                this.FormEdit = new FrmEdit();
                editControl.BaseEditModel = outStoreOrder;
                editControl.ValidatorForEdit = this.FormEdit.validatorForEdit;
                this.FormEdit.Controls.Add(editControl);
                this.FormEdit.Edit += new FrmEdit.EditEventHandler(frmEdit_Edit);
                this.FormEdit.Text = string.Format("{0}{1}", title, this.Text);
                FrmEntry.LoadAndRunDialog(this.FormEdit);
            });
        }

        #endregion

        private void FrmOutStoreOrder_Load(object sender, EventArgs e) {
            this.CreateNewThread(() => {
                this.PreventCancel = true;
                this._outStoreOrderProcessor = new OutStoreOrderProcessor(this.pceList.PageSize);
                this._searchModel = new OutStoreOrderSearchModel();
                this._pageIndex = 1;
            }, () => {
                this.WindowState = FormWindowState.Maximized;
                this.ResetForms();
                this.PreventCancel = false;
            });
        }

        private void pceList_Paging(object sender, PaginationArgs e) {
            this._pageIndex = e.PageIndex;
            this.BindOutStoreOrderList();
        }

        private void dgvOutStoreOrderList_DoubleClick(object sender, EventArgs e) {
            if (this.dgvOutStoreOrderList.CurrentRow != null) {
                int outStoreId = (int)this.dgvOutStoreOrderList.CurrentRow.Cells["Key"].Value;
                this.BindOutStoreOrderDetailsList(outStoreId);
            }
        }
    }
}
